class MapManager {
    constructor(containerId, options = {}) {
        this.map = null;
        this.mouseTool = null;
        this.currentTool = null;
        this.markers = new Map();
        this.polylines = new Map();
        this.polygons = new Map();
        this.infoWindows = new Map();
        this.layers = new Map();
        
        // 确保AMap已加载
        if (typeof AMap === 'undefined') {
            throw new Error('AMap is not loaded');
        }

        this.init(containerId, options);
    }

    // 初始化地图
    async init(containerId, options) {
        try {
            console.log('Initializing map manager...');

            // 默认配置
            const defaultOptions = {
                zoom: 12,
                center: [117.227239, 31.820587],
                viewMode: '3D',
                pitch: 0,
                mapStyle: 'amap://styles/normal',
                features: ['bg', 'point', 'road', 'building'],
                showBuildingBlock: true,
                showLabel: true,
                plugins: [
                    'AMap.ToolBar',
                    'AMap.Scale',
                    'AMap.HawkEye',
                    'AMap.MapType',
                    'AMap.Geolocation',
                    'AMap.MouseTool',
                    'AMap.PolyEditor',
                    'AMap.CircleEditor',
                    'AMap.RectangleEditor'
                ]
            };

            // 合并配置
            const mapOptions = { ...defaultOptions, ...options };

            // 创建地图实例
            this.map = new AMap.Map(containerId, mapOptions);

            // 加载插件
            await this.loadPlugins(mapOptions.plugins);

            // 初始化鼠标工具
            this.mouseTool = new AMap.MouseTool(this.map);
            this.setupMouseToolEvents();

            // 初始化图层
            this.initLayers();

            console.log('Map manager initialized successfully');
        } catch (error) {
            console.error('Failed to initialize map manager:', error);
            throw error;
        }
    }

    // 加载插件
    loadPlugins(plugins) {
        return new Promise((resolve) => {
            AMap.plugin(plugins, () => {
                // 添加基础控件
                this.map.addControl(new AMap.ToolBar());
                this.map.addControl(new AMap.Scale());
                this.map.addControl(new AMap.HawkEye({isOpen: false}));
                this.map.addControl(new AMap.MapType());
                this.map.addControl(new AMap.Geolocation());
                resolve();
            });
        });
    }

    // 初始化图层
    initLayers() {
        // 卫星图层
        this.layers.set('satellite', new AMap.TileLayer.Satellite());
        // 路网图层
        this.layers.set('roadNet', new AMap.TileLayer.RoadNet());
        // 实时路况图层
        this.layers.set('traffic', new AMap.TileLayer.Traffic());
    }

    // 切换图层显示
    toggleLayer(layerName) {
        const layer = this.layers.get(layerName);
        if (!layer) return;

        if (this.map.getLayers().includes(layer)) {
            this.map.remove(layer);
            return false;
        } else {
            this.map.add(layer);
            return true;
        }
    }

    // 设置鼠标工具事件
    setupMouseToolEvents() {
        this.mouseTool.on('draw', (event) => {
            const { obj, type } = event;
            if (!obj) return;

            switch (type) {
                case 'marker':
                    this.handleMarkerDraw(obj);
                    break;
                case 'polyline':
                    this.handlePolylineDraw(obj);
                    break;
                case 'polygon':
                    this.handlePolygonDraw(obj);
                    break;
            }

            // 重置工具状态
            this.resetTool();
        });
    }

    // 处理标记点绘制
    handleMarkerDraw(marker) {
        const id = this.generateId();
        this.markers.set(id, marker);

        // 创建信息窗体
        const infoWindow = new AMap.InfoWindow({
            content: this.createInfoWindowContent(marker),
            offset: new AMap.Pixel(0, -30)
        });

        this.infoWindows.set(id, infoWindow);

        // 点击事件
        marker.on('click', () => {
            this.openInfoWindow(id);
        });

        return id;
    }

    // 处理线段绘制
    handlePolylineDraw(polyline) {
        const id = this.generateId();
        this.polylines.set(id, polyline);

        // 计算距离
        const path = polyline.getPath();
        const distance = this.calculatePathDistance(path);

        // 创建信息窗体
        const infoWindow = new AMap.InfoWindow({
            content: `<div class="info-window">
                        <h3>距离测量</h3>
                        <p>总长度: ${MapUtils.formatDistance(distance)}</p>
                     </div>`,
            offset: new AMap.Pixel(0, -30)
        });

        this.infoWindows.set(id, infoWindow);

        // 点击事件
        polyline.on('click', (e) => {
            infoWindow.open(this.map, e.lnglat);
        });

        return id;
    }

    // 处理多边形绘制
    handlePolygonDraw(polygon) {
        const id = this.generateId();
        this.polygons.set(id, polygon);

        // 计算面积
        const path = polygon.getPath();
        const area = MapUtils.calculateArea(path.map(p => [p.getLng(), p.getLat()]));

        // 创建信息窗体
        const infoWindow = new AMap.InfoWindow({
            content: `<div class="info-window">
                        <h3>面积测量</h3>
                        <p>总面积: ${MapUtils.formatArea(area)}</p>
                     </div>`,
            offset: new AMap.Pixel(0, -30)
        });

        this.infoWindows.set(id, infoWindow);

        // 点击事件
        polygon.on('click', (e) => {
            infoWindow.open(this.map, e.lnglat);
        });

        return id;
    }

    // 开始绘制
    startDraw(type, style = {}) {
        this.resetTool();
        
        switch (type) {
            case 'marker':
                this.mouseTool.marker({
                    ...style,
                    animation: 'AMAP_ANIMATION_DROP'
                });
                break;
            case 'polyline':
                this.mouseTool.polyline({
                    strokeColor: "#FF33FF",
                    strokeOpacity: 1,
                    strokeWeight: 6,
                    ...style
                });
                break;
            case 'polygon':
                this.mouseTool.polygon({
                    strokeColor: "#FF33FF",
                    strokeOpacity: 1,
                    strokeWeight: 6,
                    fillColor: '#1791fc',
                    fillOpacity: 0.4,
                    ...style
                });
                break;
        }
        
        this.currentTool = type;
    }

    // 重置工具
    resetTool() {
        if (this.mouseTool) {
            this.mouseTool.close();
        }
        this.currentTool = null;
    }

    // 清除地图内容
    clear() {
        this.map.clearMap();
        this.markers.clear();
        this.polylines.clear();
        this.polygons.clear();
        this.infoWindows.clear();
    }

    // 打开信息窗体
    openInfoWindow(id) {
        const marker = this.markers.get(id);
        const infoWindow = this.infoWindows.get(id);
        if (marker && infoWindow) {
            infoWindow.open(this.map, marker.getPosition());
        }
    }

    // 创建信息窗体内容
    createInfoWindowContent(marker) {
        const position = marker.getPosition();
        return `<div class="info-window">
                    <h3>位置信息</h3>
                    <p>经度: ${position.getLng().toFixed(6)}</p>
                    <p>纬度: ${position.getLat().toFixed(6)}</p>
                </div>`;
    }

    // 计算路径距离
    calculatePathDistance(path) {
        let distance = 0;
        for (let i = 1; i < path.length; i++) {
            const point1 = [path[i-1].getLng(), path[i-1].getLat()];
            const point2 = [path[i].getLng(), path[i].getLat()];
            distance += MapUtils.calculateDistance(point1, point2);
        }
        return distance;
    }

    // 生成唯一ID
    generateId() {
        return 'id_' + Math.random().toString(36).substr(2, 9);
    }

    // 设置地图中心点
    setCenter(position) {
        this.map.setCenter(position);
    }

    // 设置地图缩放级别
    setZoom(zoom) {
        this.map.setZoom(zoom);
    }

    // 设置地图视角
    setViewMode(is3D) {
        this.map.setPitch(is3D ? 60 : 0);
    }

    // 添加行政区划边界
    addDistrictBoundary(districtName) {
        const districtSearch = new AMap.DistrictSearch({
            level: 'district',
            showbiz: false,
            extensions: 'all'
        });

        return new Promise((resolve, reject) => {
            districtSearch.search(districtName, (status, result) => {
                if (status === 'complete') {
                    const bounds = result.districtList[0].boundaries;
                    const polygon = new AMap.Polygon({
                        path: bounds,
                        strokeColor: '#3366FF',
                        strokeWeight: 2,
                        strokeOpacity: 0.2,
                        fillColor: '#FFF',
                        fillOpacity: 0.4
                    });
                    this.map.add(polygon);
                    resolve(polygon);
                } else {
                    reject(new Error('获取行政区划边界失败'));
                }
            });
        });
    }
}

// 导出
window.MapManager = MapManager; 